package net.starwifi.duobao.service.impl;

import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.repository.OrderRepository;
import net.starwifi.duobao.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.persistence.LockModeType;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
public class OrderServiceImpl extends BaseServiceImpl<Order,Long> implements OrderService {


    @Autowired
    OrderLogService orderLogService;

    @Autowired
    MemberService memberService;

    @Autowired
    OrderRepository repository;

    @Autowired
    TradeRecordService tradeRecordService;

    @Autowired
    CartService cartService;

    @Override
    public Order findBySn(String sn) {
        return repository.findBySn(sn);
    }


    public Order create(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo) {
        Assert.notNull(cart);
        Assert.notNull(cart.getMember());
        Assert.notEmpty(cart.getCartItems());
        Assert.notNull(receiver);
        Assert.notNull(paymentMethod);
        Assert.notNull(shippingMethod);
        Order order = build(cart, receiver, paymentMethod, shippingMethod, isInvoice, invoiceTitle, useBalance, memo);
        if (paymentMethod.getMethod() == PaymentMethod.Method.online) {
            order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
        }
        order.setIsAllocatedStock(true); //锁定库存
        em.persist(order);
        OrderLog orderLog = new OrderLog();
        orderLog.setType(OrderLog.Type.create);
        orderLog.setOperator(null);
        orderLog.setOrder(order);
        orderLogService.save(orderLog);
        //账户余额操作,增加余额扣款记录
        Member member = cart.getMember();
        if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) {
            //扣除账户已经付款的金额
            memberService.lock(member, LockModeType.PESSIMISTIC_WRITE);
            member.setBalance(member.getBalance().subtract(order.getAmountPaid()));
            memberService.update(member);
            TradeRecord tradeRecord=new TradeRecord();
            tradeRecord.setType(1);
            tradeRecord.setFee(order.getAmountPaid());
            tradeRecord.setRemarks("订单余额支付支出");
            tradeRecord.setOutSn(order.getSn());
            tradeRecord.setTradeCat(2);//购物
            tradeRecord.setSn("sn");
            tradeRecord.setMemberId(member.getId());
            tradeRecordService.save(tradeRecord);
        }
        //库存操作

        //清空购物车
        cartService.clear();
        return order;
    }

    @Override
    public Order build(PaymentMethod paymentMethod,BigDecimal productAmount, String sn,int orderType, Member member) {
        Order order=new Order();
        order.setSn(sn);
        order.setOrderStatus(0); //订单确认
        order.setPaymentStatus(0); //未支付
        order.setShippingStatus(0);  //等待出单
       // order.setPrice(productAmount);
        order.setFee(new BigDecimal(0));
        order.setOrderType(orderType);
        order.setOffsetAmount(new BigDecimal(0));
        order.setProductName("B币购买");
        order.setPaymentMethod(paymentMethod);
        order.setMemberId(member.getId());
        order.setMemberName(member.getMobile());
        save(order);
        flush();
        OrderLog orderLog = new OrderLog();
        orderLog.setType(OrderLog.Type.create);
        orderLog.setOrder(order);
        orderLog.setContent("[系统:]订单已经创建!");
        orderLogService.save(orderLog);
        return order;
    }


    @Transactional(readOnly = true)
    public Order build(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo) {
        Assert.notNull(cart);
        Assert.notNull(cart.getMember());
        Assert.notEmpty(cart.getCartItems());
        Order order = new Order();
        order.setShippingStatus(0);
        order.setFee(new BigDecimal(0));
        order.setOffsetAmount(new BigDecimal(0));
        order.setMemo(memo);
        order.setMemberId(cart.getMember().getId());
        if (receiver != null) {
            order.setConsignee(receiver.getConsignee());
            order.setAreaName(receiver.getAreaName());
            order.setAddress(receiver.getAddress());
            order.setZipCode(receiver.getZipCode());
            order.setPhone(receiver.getPhone());
            order.setArea(receiver.getArea());
        }
        order.setPaymentMethod(paymentMethod);
        if (shippingMethod != null && paymentMethod != null ) {
            BigDecimal freight = shippingMethod.calculateFreight(cart.getWeight());
            order.setFreight(freight);
            order.setShippingMethod(shippingMethod);
        } else {
            order.setFreight(new BigDecimal(0));
        }
        List<OrderItem> orderItems = order.getOrderItems();
        for (CartItem cartItem : cart.getCartItems()) {
            if (cartItem != null && cartItem.getProduct() != null) {
                Product product = cartItem.getProduct();
                OrderItem orderItem = new OrderItem();
                orderItem.setSn(product.getSn());
                orderItem.setName(product.getName());
                orderItem.setFullName(product.getFullName());
                orderItem.setPrice(cartItem.getPrice());
                orderItem.setWeight(product.getWeight());
                orderItem.setThumbnail(product.getThumbnail());
                orderItem.setIsGift(false);
                orderItem.setQuantity(cartItem.getQuantity());
                orderItem.setShippedQuantity(0);
                orderItem.setReturnQuantity(0);
                orderItem.setProduct(product);
                orderItem.setOrder(order);
                orderItems.add(orderItem);
            }
        }
        if (StringUtils.isNotEmpty(invoiceTitle)) {
            order.setIsInvoice(true);
            order.setInvoiceTitle(invoiceTitle);
           // order.setTax(order.calculateTax());
        } else {
            order.setIsInvoice(false);
            order.setTax(new BigDecimal(0));
        }
        order.setOrderStatus(0);
        order.setPaymentStatus(0);
        if (paymentMethod != null && paymentMethod.getTimeout() != null && order.getPaymentStatus() == 0) {
            order.setExpire(DateUtils.addMinutes(new Date(), paymentMethod.getTimeout()));
        }
        return order;
    }


    /** 订单支付 */
    @Transactional
    public void payment(final Order order, Payment payment) {
        Assert.notNull(order);
        Assert.notNull(payment);
        //payment.setOrder(order);
        order.setPaymentStatus(1); //支付成功
        update(order);
        OrderLog orderLog = new OrderLog(order,OrderLog.Type.payment,"[支付成功]话费购,您的订单支付成功");
        orderLogService.save(orderLog);
    }


}
